package _base0to1;

import java.util.ArrayList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 */
public class No54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans;

        int up = 0, down = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;

        while (true) {
            for (int i = left; i <= right; i++) { // 左->右
                ans.add(matrix[up][i]);
            }
            if (++up > down) break;
            for (int i = up; i <= down; i++) { // 上->下
                ans.add(matrix[i][right]);
            }
            if (--right < left) break;
            for (int i = right; i >= left; i--) { // 右->左
                ans.add(matrix[down][i]);
            }
            if (--down < up) break;
            for (int i = down; i >= up; i--) { // 下->上
                ans.add(matrix[i][left]);
            }
            if (++left > right) break;
        }
        return ans;
    }
}
